import java.util.zip.*;
import java.io.*;
import java.net.URL;

public class testZip
{
	static final int BUFFER = 2048;
	public static void main (String argv[])
	{
		if(argv.length < 2){
			System.out.println("Usage: java testZip <archivename> <file1> <file2> .... <filen>");
			System.exit(0);
		}
		byte data[] = new byte[BUFFER];
		try{
			String archiveName = argv[0];
			FileOutputStream dest = new FileOutputStream(archiveName);
			ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(dest));

			for(int i = 1; i < argv.length; i++)
			{
				String inFileName = argv[i];
				//add a file to the zip file
				System.out.println("Adding " + inFileName + " to zip archive");
				BufferedInputStream origin;
				if (! inFileName.contains("http"))
				{
					//read from a local file
					FileInputStream fin = new FileInputStream(inFileName);
					origin = new BufferedInputStream(fin, BUFFER);
				}else{ 
					//Read from a URL
					URL fileURL = new URL(inFileName);
					origin = new BufferedInputStream(fileURL.openStream(), BUFFER);
				}
				//The name given to ZipEntry only determines the path to the file withn the
				//zip.  if you give the full file path or URL, the hierarchy will be replicated
				//in the zip, which may or may not be desireable.  This code here will remove the
				//directory structure and put everything in the zip root directory.
				String nameInZipFile = new File(inFileName).getName();
				ZipEntry entry = new ZipEntry(nameInZipFile);
				out.putNextEntry(entry);

				int count;
				while((count = origin.read(data, 0, BUFFER)) != -1)
				{
					out.write(data, 0 , count);
				}
				origin.close();
			}
			out.close();
		}catch(Exception e){
			e.printStackTrace();
		}
	}
}
